﻿using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;

namespace roslynCodeReview
{
    /// <summary>
    /// T001:类名定义不能过短。
    /// </summary>
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    internal class DiagnosticAnalyzer01 : DiagnosticAnalyzer
    {
        public DiagnosticDescriptor Rule
        {
            get
            {
                if (_descriptor == null)
                {
                    _descriptor = new DiagnosticDescriptor(
                        "T001",
                        "类名定义不能过短。",
                        "类名定义不能过短。",
                        "Test",
                        DiagnosticSeverity.Error,
                        true);
                }
                return _descriptor;
            }
        }
        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

        private DiagnosticDescriptor _descriptor;
  

        public override void Initialize(AnalysisContext context)
        {
            // Initialization logic here
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
            //注册类定义语法回调
            context.RegisterSyntaxNodeAction(OnSyntaxNodeAction, SyntaxKind.ClassDeclaration);


        }


        //当任意类定义语法编译时，将回调此方法
        private void OnSyntaxNodeAction(SyntaxNodeAnalysisContext context)
        {
            ClassDeclarationSyntax classDeclaration = (ClassDeclarationSyntax)context.Node;

            //发现类名过短
            if (classDeclaration.Identifier.ToString().Length <= 3)
            {
                //上报分析器
                context.ReportDiagnostic(Diagnostic.Create(Rule, classDeclaration.Identifier.GetLocation()));
            }

        }
    }
}
